<template>
  <!-- 只读状态显示 -->
  <span v-if="readonly" :style="readonlyStyle">
    {{ displayValue }}
  </span>

  <!-- 可编辑状态显示 -->
  <div v-else class="input-container">
    <el-input :model-value="inputValue" v-bind="inputAttrs" ref="inputRef" @blur="$emit('blur', $event)"
      @keydown="$emit('keydown', $event)" @update:modelValue="handleInput" :disabled="disabled"
      :placeholder="placeholder" :maxlength="maxlength" :show-word-limit="showWordLimit" :type="inputType"
      :clearable="clearable" :style="{ width: width }" :class="[{ 'cell-input': noBorder }]" />
    <slot></slot>
  </div>
</template>

<script>
import { Definition } from '../../engine/common/definition';
import { Util } from '../../utils/util';
export default {
  name: 'TableCellInput',
  inheritAttrs: false, // Important: Prevent automatic attribute inheritance
  props: {
    // 用于excelCell 选中cell 时，首次输入值，
    // 该值需要触发一次 update 通知上级控件处理这个输入变更
    // 引用夫控件需要在update 事件收到后，及时清空该值，不然一致显示该值
    excelCellStartEditValue: {
      type: [String, Number],
      default: null
    },
    modelValue: {
      type: [String, Number],
      required: true
    },
    placeholder: {
      type: String,
      default: ''
    },
    disabled: {
      type: Boolean,
      default: false
    },
    readonly: {
      type: Boolean,
      default: false
    },
    maxlength: {
      type: Number,
      default: null
    },
    showWordLimit: {
      type: Boolean,
      default: false
    },
    numberMode: {
      type: Boolean,
      default: false
    },
    precision: {
      type: Number,
      default: null
    },
    isFundType: {
      type: Boolean,
      default: false
    },
    // 0 作为空，只读时显示 --
    zeroAsBlank: {
      type: Boolean,
      default: true
    },
    width: {
      type: String,
      default: '100%'
    },
    readonlyWidth: {
      type: String,
      default: null
    },
    clearable: {
      type: Boolean,
      default: false
    },
    remarkMode: {
      type: Boolean,
      default: false
    },
    // 新增样式相关属性
    backgroundColor: {
      type: String,
      default: ''
    },
    borderColor: {
      type: String,
      default: ''
    },
    borderWidth: {
      type: String,
      default: ''
    },
    borderRadius: {
      type: String,
      default: ''
    },
    fontSize: {
      type: String,
      default: ''
    },
    textAlign: {
      type: String,
      default: 'left'
    },
    padding: {
      type: String,
      default: ''
    },
    containerClass: {
      type: [String, Object, Array],
      default: ''
    },
    inputStyle: {
      type: [String, Object, Array],
      default: () => ({})
    },

    // 是否包含边框
    noBorder: {
      type: Boolean,
      default: false
    }
  },

  emits: ['update:modelValue', 'blur', 'keydown'],

  watch: {
    modelValue(val) {
      this.inputValue = this.excelCellStartEditValue ?? val;
    },

    /*
    excelCellStartEditValue(val) {
      console.log('InputCell watch excelCellStartEditValue --> ', val);
      if (val != null) {
        this.inputValue = val;
        this.$nextTick(() => {
          this.$emit('update:modelValue', val);
        });
      }
    }
    */
  },

  data() {
    return {
      inputValue: this.excelCellStartEditValue !== null ? this.excelCellStartEditValue : this.modelValue,
    }
  },

  mounted() {
    // 如果有cell 初始值，通知更新
  if (this.excelCellStartEditValue !== null) {
    this.$nextTick(() => {
      this.$emit('update:modelValue', this.excelCellStartEditValue);
    });
  }
},

  computed: {
    // Separate attributes for container and input elements
    containerAttrs() {
      const { class: cls, ...attrs } = this.$attrs;
      return attrs;
    },
    inputAttrs() {
      // Filter out attributes that should go to container
      const containerAttrs = ['class'];
      const inputAttrs = {};
      for (const [key, value] of Object.entries(this.$attrs)) {
        if (!containerAttrs.includes(key)) {
          inputAttrs[key] = value;
        }
      }
      return inputAttrs;
    },
    computedInputStyle() {
      // Build style object from props
      const style = {};

      if (this.backgroundColor) style.backgroundColor = this.backgroundColor;
      if (this.borderColor) style.borderColor = this.borderColor;
      if (this.borderWidth) style.borderWidth = this.borderWidth;
      if (this.borderRadius) style.borderRadius = this.borderRadius;
      if (this.fontSize) style.fontSize = this.fontSize;
      if (this.textAlign) style.textAlign = this.textAlign;
      if (this.padding) style.padding = this.padding;

      return [this.inputStyle, style];
    },
    inputType() {
      return this.remarkMode ? 'textarea' :
        this.numberMode ? 'number' :  // 可扩展其他类型
          'input'
    },

    displayValue() {
      if (this.isFundType) {
        return Util.getFundString(this.modelValue || 0);
      }

      else {
        if (this.zeroAsBlank && (this.modelValue === 0 || this.modelValue === '0')) {
          return '--';
        }
        else {
          return this.modelValue ?? "";
        }
      }
    },

    inputMaxLength() {
      if (this.maxLength) {
        return this.maxLength;
      } else {
        return this.remarkMode ? Definition.maxTextLenForRemark : Definition.maxTextLenForCommonTextfield;
      }
    },
    readonlyStyle() {
      if (this.readonlyWidth) {
        return { width: this.readonlyWidth, display: 'inline-block' };
      }
      return {};
    },
  },

  methods: {
    handleInput(value) {
      this.inputValue = value;
      if (this.numberMode) {
        // 只有负号，不处理
        if (value === '-') {
          return;
        }
        try {
          value = Number(value)
          if (this.precision) {
            value = Util.convertWithPrecision(value, this.precision, true)
          }
          this.inputValue = value; // 更新inputValue 因为精度截断后，inputValue 会被截断，所以需要更新inputValue
        } catch (e) {
          console.error("TableCellInput handle number input error: ", e);
        }
      }
      this.$emit('update:modelValue', value)
    },

    focus() {
      this.$refs.inputRef?.focus();
    }
  }
}
</script>

<style scoped>
.input-container {
  display: block;
  width: 100%;
  text-align: left;
}

.input-container :deep(.el-input) {
  width: 100%;
}

.input-container :deep(.el-input__inner) {
  text-align: left !important;
}

/* 隐藏数字模式下的右侧增减箭头 */
:deep(.el-input__inner::-webkit-outer-spin-button),
:deep(.el-input__inner::-webkit-inner-spin-button) {
  -webkit-appearance: none;
  margin: 0;
}

:deep(.el-input__inner[type="number"]) {
  -moz-appearance: textfield;
  appearance: textfield;
}

.cell-input {
  width: 100%;
  height: 100%;
}

.cell-input :deep(.el-input__wrapper) {
  box-shadow: none;
  border: none;
  padding: 0 0px;
  height: 100%;
  background-color: #e6f7ff;
}
</style>